const {HttpException} = require('./HttpException');
const catchError = async (ctx, next) => {
  try {
    await next()
  } catch (error) {
    //TODO console.log('error:',error)  Error: next() called multiple times
    /*
      function dispatch (i) {
      if (i <= index) return Promise.reject(new Error('next() called multiple times'))
    */
    const isHttpException = error instanceof HttpException;
    const isDev = process.env.NODE_ENV;

    // 开发过程中出现的不可预知的错误↓
    if (isDev && !isHttpException) {
      throw error
    }

    // 我们手动抛出的,要返回给客户端知道的信息(包括success)
    if (isHttpException) {
      ctx.body = {
        msg: error.msg
        , errno: error.errno
        , request: `${ctx.method} ${ctx.path}`
        , data: error.data
      };
      ctx.status = error.code

      // 服务器已经上线了 但出现了未知错误 需要后端去修复
    } else {
      ctx.body = {
        msg: 'unkonw error'
        , errno: 999999999
        , request: `${ctx.method} ${ctx.path}`
      };
      ctx.status = 500
    }
  }
};

module.exports = catchError;
